import Promise from 'promise';
import * as ResultMsg from '../constrants/ResultMsg';
import { AudioModel } from '../models';

const fields = '_id type title describe url';

export function find(appId, conditions, options) {
  if (typeof appId !== 'string') throw new Error(ResultMsg.NO_APP_ID);
  if (typeof conditions !== 'object') throw new Error(ResultMsg.NOT_OBJECT);
  if (typeof options !== 'object') options = null;
  conditions.appId = appId;
  const query = AudioModel.find(conditions).select(fields).setOptions(options);
  return query.exec();
}

export function findOne(appId, conditions, options) {
  if (typeof appId !== 'string') throw new Error(ResultMsg.NO_APP_ID);
  if (typeof conditions !== 'object') throw new Error(ResultMsg.NOT_OBJECT);
  if (typeof options !== 'object') options = null;
  conditions.appId = appId;
  const query = AudioModel.findOne(conditions).select(fields).setOptions(options);
  return query.exec();
}

export function findOneById(appId, id) {
  if (typeof appId !== 'string') throw new Error(ResultMsg.NO_APP_ID);
  if (typeof id !== 'string' && typeof id !== 'object') throw new Error(ResultMsg.NO_ID);
  const query = AudioModel.findOne({appId: appId, _id: id }).select(fields);
  return query.exec();
}

export function update(appId, id, data) {
  if (typeof appId !== 'string') throw new Error(ResultMsg.NO_APP_ID);
  if (typeof id !== 'string' && typeof id !== 'object') throw new Error(ResultMsg.NO_ID);
  if (typeof data !== 'object') throw new Error(ResultMsg.NOT_OBJECT);
  const query = AudioModel.findByIdAndUpdate(id, { $set: data });
  return query.exec();
}

export function create(appId, {type, title, describe, url}) {
  if (typeof appId !== 'string') throw new Error(ResultMsg.NO_APP_ID);
  if (typeof type !== 'string'
    || typeof title !== 'string'
    || typeof describe !== 'string'
    || typeof url === 'string') {
    throw new Error(ResultMsg.NOT_STRING)
  }

  const doc = new AudioModel();
  doc.appId = appId;
  doc.type = type;
  doc.title = title;
  doc.describe = describe;
  doc.url = url;
  return doc.save();
}

export function remove(appId, conditions) {
  if (typeof appId !== 'string') throw new Error(ResultMsg.NO_APP_ID);
  if (typeof conditions !== 'object') throw new Error(ResultMsg.NOT_OBJECT);
  conditions.appId = appId
  return AudioModel.find(conditions).remove().exec();
}

export async function removeById(appId, id) {
  if (typeof appId !== 'string') throw new Error(ResultMsg.NO_APP_ID);
  if (typeof id !== 'string' && typeof id !== 'object') throw new Error(ResultMsg.NO_ID);
  return AudioModel.find({appId: appId, _id: id}).remove().exec();
}
